;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Sales.PurchaseApply", [])
        .controller("PurchaseApplyCtrl", ["$scope", "$state", "$stateParams", "ybWidget", "ybHttp", "MESG_TYPE", "UserContextService", "Upload", "$timeout", "EventBus", "$filter", function ($scope, $state, $stateParams, ybWidget, ybHttp, MESG_TYPE, UserContextService, Upload, $timeout, EventBus, $filter) {
            $scope.activeFlag = [true, false, false, false, false];
            $scope.subTabFlag = [true, false];
            $scope.datePickerFlag = [false, false];
            $scope.TJJXList = [];
            $scope.markInfo = {
                allCheckedBill: false,
                allCheckedMaterial: false,
                curRow: -1
            };
            $scope.submitted = false;
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.condition = {
                seller: true,
                isService :$scope.isTJ? $scope.curUser.isService:undefined
            };
            // 展示价格方案
            $scope.showPricePlan = true            
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                showMateriel: false
            };
            $scope.dataList = [];
            $scope.orderObj = {
                materialsList: [],
                isDirectCast: 0,
                forward: 0,
                isImprove: 0
            };
            $scope.purchaseLevelList = [];
            $scope.billStateList = [];
            $scope.syncCrmFlagList = [{
                    name: '未同步',
                    value: 0
                },
                {
                    name: '同步成功',
                    value: 1
                },
                {
                    name: '同步失败',
                    value: 2
                }
            ];
            // 送货单创建状态
            $scope.sendStatusList = [{
                    name: '未创建',
                    value: 0
                },
                {
                    name: '部分创建',
                    value: 1
                },
                {
                    name: '已创建',
                    value: 2
                }
            ];

            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/purchaseRequest/export"),
                sectionParam: {
                    billIds: []
                },
                allUrl: ybHttp.RequestUrl("device", "/purchaseRequest/exportAll")
            };
            $scope.tableConfig = {
                fixedWidth: 200,
                scrollWidth: 1580,
                tableCol: [
                    {
                        type: "",
                        name: "采购单号",
                        dataField: "billNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortField: "bill_no",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "CRM单号",
                        dataField: "crmOrder",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户名称",
                        dataField: "purchaseOrgName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "purchase_org_name",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "接收单位",
                        dataField: "supplierOrgName",
                        width: 180,
                        isShow: $scope.isZL,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "是否直投订单",
                        dataField: "isDirectCastShow",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购方式",
                        dataField: "purchaseTypeShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "type_desc",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购金额",
                        dataField: "totalValue",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "total_value",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "发运方式",
                        dataField: "sendType",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "shipping_method",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调度员",
                        dataField: "dispatcherName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "dispatcher_name",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请时间",
                        dataField: "createDateShow",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "create_date",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "提交时间",
                        dataField: "submitDateShow",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "submit_date",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核状态",
                        dataField: "statusDesc",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "bill_status",
                        sortType: "",
                        isEN: true
                    },
                    {
                        type: "",
                        name: "审核人",
                        dataField: "auditName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "audit_name",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "create_name",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核时间",
                        dataField: "auditDateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "audit_date",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核意见",
                        dataField: "auditMessage",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortField: "audit_message",
                        sortType: ""
                    },
                    {
                        type: "synCrm",
                        name: "同步CRM",
                        dataField: "syncCrmFlagShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewCrmError",
                        toSort: true,
                        sortField: "sync_crm_flag",
                        sortType: ""
                    },
                    {
                        type: "attach",
                        name: "附件",
                        dataField: "attachName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        clickFn: "downloadAttach",
                        sortType: ""
                    },
                    {
                        name: "是否删除",
                        dataField: "delShow",
                        width: 100,
                        isShow: $scope.isWJ,
                        isFixed: false,
                    },
                    {
                        name: "删除时间",
                        dataField: "updateDateShow",
                        width: 140,
                        isShow: $scope.isWJ,
                        isFixed: false,
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 160,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.materielTableConfig = {
                scrollWidth: 870,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        needInput: false,
                    },
                    {
                        name: "自定义零件编号",
                        width: 150,
                        dataField: "customMaterialsNo",
                        needInput: false,
                    },   
                    {
                        name: "未发货数量",
                        width: 150,
                        dataField: "noDeliveredQty",
                        isShow:$scope.isCHY,
                        needInput: false,
                    },
                    {
                        name: "上次采购时间",
                        width: 150,
                        dataField: "lastPurchaseTime",
                        isShow:$scope.isCHY,
                        needInput: false,
                    },
                    {
                        name: "本年度采购数量",
                        width: 150,
                        dataField: "thisYearPurchaseAmount",
                        isShow:$scope.isCHY,
                        needInput: false,
                    },                    
                    {
                        name: "零件属性",
                        width: 150,
                        dataField: "productPropClass",
                        needInput: false,
                    },                                        
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        needInput: false,
                    },
                    {
                        name: "零件分类",
                        width: 120,
                        dataField: "materialsType",
                        needInput: false
                    },
                    {
                        name: "适用机型",
                        width: 150,
                        dataField: "machineModel",
                        isShow:$scope.isJCHK,
                        needInput: true,
                    },
                    {
                        name: "申请数量",
                        width: 100,
                        dataField: "qty",
                        needInput: true,
                    },
                    {
                        name: "已出库数量",
                        width: 100,
                        dataField: "inventoryOutAmount",
                        needInput: true,
                        isShow:$scope.isDL || $scope.isZHL,
                    },
                    {
                        name: "内部库存",
                        width: 100,
                        dataField: "totalInner",
                        isShow: $scope.isDL || $scope.isZHL,
                    },
                    {
                        name: "外部库存",
                        width: 100,
                        dataField: "totalOuter",
                        isShow: $scope.isDL || $scope.isZHL,
                        clickFn: 'waibuStock'
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        needInput: false,
                    },
                    {
                        name: "参考单价",
                        width: 120,
                        dataField: "price",
                        needInput: false,
                    },
                    {
                        name: "价格方案",
                        width: 150,
                        dataField: "priceSchemeName",
                        needInput: true,
                    },
                    {
                        name: "交货日期",
                        width: 120,
                        dataField: "deliveryDateStr",
                        needInput: $scope.isDL || $scope.isZHL,
                        inputType: 'time'
                    },
                    {
                        name: "成交单价",
                        width: 120,
                        dataField: "settlementPrice",
                        needInput: false,
                    },
                    {
                        name: "合计",
                        width: 150,
                        dataField: "applyTotalPrice",
                        needInput: false,
                    },
                    {
                        name: "替换零件",
                        width: 150,
                        needWarn: true,
                        dataField: "replaceMaterialsNo",
                    },
                    {
                        name: "替换零件中文名",
                        width: 150,
                        needWarn: true,
                        dataField: "replaceMaterialsDes",
                    },
                    {
                        name: "替换描述",
                        width: 150,
                        needWarn: true,
                        dataField: "replaceMaterialsNote",
                    },
                    {
                        name: "备注",
                        width: 150,
                        dataField: "remark",
                        needInput: true,
                    },
                    {
                        name: "标准交期",
                        width: 150,
                        dataField: "standDeliveryTime",
                    },
                    {
                        name: "预计发货日期",
                        dataField: "estimatedShippingDateShow",
                        width: 130,
                    }
                ]
            };

            $scope.auditMaterielTableConfig = {
                scrollWidth: 1000,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 120,
                        dataField: "materialsNo",
                        needInput: false
                    },
                    {
                        name: "自定义零件编号",
                        width: 120,
                        dataField: "customMaterialsNo",
                        needInput: false
                    },                    
                    {
                        name: "零件中文名",
                        width: 170,
                        dataField: "materialsDes",
                        needInput: false
                    },
                    {
                        name: "零件分类",
                        width: 120,
                        dataField: "materialsType",
                        needInput: false
                    },
                    {
                        name: "是否直投",
                        width: 120,
                        dataField: "isDirectCastShow",
                        needInput: false
                    },
                    {
                        name: "申请数量",
                        width: 80,
                        dataField: "qty",
                        needInput: false
                    },
                    {
                        name: "内部库存",
                        width: 100,
                        dataField: "totalInner",
                        isShow: $scope.isDL || $scope.isZHL,
                    },
                    {
                        name: "外部库存",
                        width: 100,
                        dataField: "totalOuter",
                        isShow: $scope.isDL || $scope.isZHL,
                        clickFn: 'waibuStock'
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        needInput: false
                    },
                    {
                        name: "参考单价",
                        width: 120,
                        dataField: "price",
                        needInput: false
                    },
                    {
                        name: "价格方案",
                        width: 150,
                        dataField: "priceSchemeName",
                        needInput: false,
                        input: true,
                        inputType: "func"
                    },
                    {
                        name: "交货日期",
                        width: 120,
                        dataField: "deliveryDateStr",
                        needInput: false
                    },
                    {
                        name: "是否加价",
                        width: 80,
                        dataField: "isNeedRaise",
                        hidden: true,
                        input: true,
                        inputType: "jiajia",
                        isChecked: "",
                    },
                    {
                        name: "成交单价",
                        width: 100,
                        dataField: "settlementPrice",
                        needInput: false
                    },
                    {
                        name: "合计",
                        width: 120,
                        dataField: "applyTotalPrice",
                        needInput: false
                    },
                    {
                        name: "适用机型",
                        width: 100,
                        dataField: "machineModel",
                        needInput: false
                    },
                    {
                        name: "替换零件",
                        width: 150,
                        needWarn: true,
                        dataField: "replaceMaterialsNo",
                        toSort: true,
                    },
                    {
                        name: "替换零件中文名",
                        width: 150,
                        needWarn: true,
                        dataField: "replaceMaterialsDes"
                    },
                    {
                        name: "替换描述",
                        width: 150,
                        needWarn: true,
                        dataField: "replaceMaterialsNote"
                    },
                    {
                        name: "库存满足数量",
                        width: 110,
                        dataField: "inventoryProvideQty",
                        needInput: true
                    },
                    {
                        name: "采购员处理数量",
                        width: 120,
                        dataField: "buyerDealQty",
                        needInput: true
                    },
                    {
                        name: "代理商间拨数量",
                        width: 120,
                        dataField: "agentProvideQty",
                        needInput: true
                    },
                    {
                        name: "标准交期",
                        width: 150,
                        dataField: "standDeliveryTime",
                    },
                    {
                        name: "预计发货日期",
                        dataField: "estimatedShippingDateShow",
                        width: 130,
                    },
                    {
                        name: "调整后数量",
                        dataField: "saleAdjustQty",
                        width: 100,
                    },
                    {
                        name: "已出库数量",
                        width: 100,
                        dataField: "inventoryOutAmount",
                        needInput: false,
                        isShow:$scope.isDL || $scope.isZHL,
                    },
                    {
                        name: "备注",
                        dataField: "remark",
                        width: 100,
                    },
                    {
                        name: "是否删除",
                        dataField: "saleDelStatusShow",
                        width: 100,
                    },
                    {
                        name: "删除时间",
                        dataField: "saleDelTimeShow",
                        width: 140,
                    },
                    {
                        name: "外部变更人",
                        dataField: "sapChangeName",
                        width: 130,
                    },
                    {
                        name: "外部变更日期",
                        dataField: "sapChangeDate",
                        width: 130,
                    }
                ]
            };

            $scope.toSort4audit = function (config, index) {
                if (!config[index].toSort) {
                    return;
                }
                var sortTypeRes = ybWidget.ToSort(config, index);
                var sortFiledObj = config[index];
                handleSort(sortFiledObj.sortField || sortFiledObj.dataField, sortTypeRes, $scope.orderObj.materialsList)
            };

            function handleSort(sortFieldKey, sortType, data = []) {
                if (sortFieldKey == 'replaceMaterialsNo') { // 替换零件的排序
                    data.sort(function (a, b) {
                        const aRepMaterial = a.replaceMaterialsNo || ''
                        const bRepMaterial = b.replaceMaterialsNo || ''
                        const aLength = aRepMaterial.split(',').length
                        const bLength = bRepMaterial.split(',').length
                        if (aLength == bLength) {
                            return 0
                        }
                        if (aLength > bLength) {
                            return sortType == 'asc' ? 1 : -1;
                        }
                        if (aLength < bLength) {
                            return sortType == 'asc' ? -1 : 1;
                        }
                    });
                }
            }

            $scope.rejectRecordTableConfig = {
                scrollWidth: 870,
                tableCol: [{
                        name: "操作人",
                        width: 150,
                        dataField: "operationName",
                        needInput: false
                    },
                    {
                        name: "操作时间",
                        width: 100,
                        dataField: "operationTimeShow",
                        needInput: false
                    },
                    {
                        name: "驳回信息",
                        width: 120,
                        dataField: "message",
                        needInput: false
                    }
                ]
            };

            $scope.showDatepicker = false;

            $scope.tabFlag = {};
            $scope.params = $stateParams
            var sortParam = "";
            var sortFiled = {};
            var tabFlag = {
                0: "采购申请详情",
                1: "新增采购申请",
                2: "编辑采购申请"
            };

            var btnPermissionCode = {
                purchaseApplyAdd: window.ActionCode.purchaseApplyAdd,
                purchaseApplySynCRM: window.ActionCode.purchaseApplySynCRM,
                purchaseApplyDel: window.ActionCode.purchaseApplyDel,
                purchaseApplyEdit: window.ActionCode.purchaseApplyEdit,
                purchaseApplyAudit: window.ActionCode.purchaseApplyAudit,
                purchaseApplyExport: window.ActionCode.purchaseApplyExport,
                purchaseApplyImport: window.ActionCode.purchaseApplyImport,
                purchaseApplyAdjustPrice: window.ActionCode.purchaseApplyAdjustPrice,
            };

            $scope.btnPermission = {
                purchaseApplyAdd: true,
                purchaseApplySynCRM: true,
                purchaseApplyDel: true,
                purchaseApplyEdit: true,
                purchaseApplyAudit: true,
                purchaseApplyExport: true,
                purchaseApplyImport: true,
                purchaseApplyAdjustPrice: true,
            };

            $scope.tableCol = $scope.auditMaterielTableConfig.tableCol;

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
                $scope.selfMadeFlag = UserContextService.CheckPermission([window.ActionCode.purchaseApplySelfMade]);
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    scrollLeft: { left: $scope.tableConfig.fixedWidth + "px" },
                    scrollLeftWidth: { width: $scope.tableConfig.fixedWidth + "px" }
                };
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        $scope.submitted = false;
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    case 3:
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.tabFlag = {};
                $scope.orderObj = {
                    materialsList: [],
                    isDirectCast: 0,
                    forward: 0,
                    isImprove: 0
                };
                $scope.markInfo.allCheckedMaterial = false;
                $scope.toolbarConfig.showMateriel = false;
            }

            function getDataList(curPage) {
                if (!$scope.condition.dispatcherName) {
                    $scope.condition.dispatcherId = "";
                }
                $scope.markInfo = {
                    allCheckedBill: false,
                    allCheckedMaterial: false,
                    curRow: -1
                };
                $scope.exportParam.sectionParam.billIds = [];
                var service = "device";
                var reqUrl = "/purchaseRequest/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                if (!!sortParam && sortParam.indexOf("undefined") !== -1) {
                    param.sort = sortParam;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = {
                    ...$scope.condition,
                    seller: true,
                    selfMade: 0,
                    materialNoList: !!$scope.condition.materialNos ? $scope.condition.materialNos.split(/\s+/) : []
                };
                if (!!$scope.selfMadeFlag) {
                    param.filters.selfMade = 1;
                }
                if ($scope.isZL) {
                    param.filters.zhilianFlag = true
                }
                if ($scope.isTJ) {
                    if ($scope.isSuperAdmin) {
                        param.filters.selfMade = 0;
                    }
                    param.filters.isService = $scope.curUser.isService
                }
                
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.auditDateShow = $filter("YbDate")(item.auditDate, 'yyyy-MM-dd HH:mm:ss');
                        item.syncCrmFlagShow = $filter("ProgressStatus")(item.syncCrmFlag, "sap");
                        item.createDateShow = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.submitDateShow = $filter("YbDate")(item.submitDate, 'yyyy-MM-dd HH:mm:ss');
                        item.isDirectCastShow = $filter("TrueOrFalse")(item.isDirectCast);
                        item.purchaseTypeShow = item.purchaseTypeChildId ? item.typeDesc + "-" + item.purchaseTypeChildName : item.typeDesc;
                        item.sendType = item.sendTypeChildId ? item.shippingMethod + "-" + item.sendTypeChildName : item.shippingMethod;
                        item.delShow = $filter("TrueOrFalseOrNull")(item.del);
                        if (item.del) {
                            item.updateDateShow = $filter("YbDate")(item.updateDate, 'yyyy-MM-dd HH:mm:ss');
                        }
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.toSort = function (config, index) {
                if (!config[index].toSort) {
                    return;
                }
                var sortType = ybWidget.ToSort(config, index);
                sortFiled = config[index];
                sortParam = sortFiled.sortField + " " + sortType;
                getDataList(1);
            };

            function clearSortParam() {
                sortParam = "";
                if (angular.isDefined(sortFiled.sortType)) {
                    sortFiled.sortType = ""
                }
            }

            $scope.refreshData = function () {
                clearSortParam();
                getDataList(1);
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        ybWidget.GetTableCol($scope.auditMaterielTableConfig.tableCol, 'priceSchemeName').hidden = $scope.needHide;
                        viewDetail(item);
                        break;
                    case "viewCrmError":
                        viewSapError(item);
                        break;
                    case "downloadAttach":
                        downloadAttach(item);
                        break;
                    case "waibuStock":
                        waibuStock(item);
                        break;
                    default:
                        break;
                }
            };

            function viewSapError(item) {
                ybWidget.ShowMessage(item.syncCrmMsg, MESG_TYPE.Note);
            }

            function downloadAttach(item) {
                window.location.href = ybHttp.RequestUrl("device", "/purchaseRequest/downloadAttach") + '?billId=' + item.billId;
            }

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {
                    seller: true,
                    isService :$scope.isTJ? $scope.curUser.isService:undefined
                };

                if ($scope.isWJ) {
                    $scope.condition.showDel = true
                }
            };

            $scope.clearCondition = function () {
                $scope.condition.dispatcherName = "";
            };

            function getBillIds() {
                $scope.exportParam.sectionParam.billIds = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.billIds.push(item.billId);
                    }
                });
            }

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
                getBillIds();
            };

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                getBillIds();
            };

            $scope.addApply = function () {
                $scope.tabFlag.type = 0;
                $scope.tabFlag.name = tabFlag[1];
                $scope.orderObj.createDate = +new Date();
                $scope.orderObj.supplierOrgId = $scope.curOrgId;
                $scope.orderObj.supplierOrgName = $scope.curOrg.companyName;
                $scope.changeTab(2);
            };

            $scope.synCRMApply = function () {
                var ids = [];
                /* 同步按钮权限：已经审核通过，未同步、同步失败的数据才可以同步 */
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!!$scope.dataList[i].isChecked) {
                        if ($scope.dataList[i].syncCrmFlag !== '1') { // $scope.dataList[i].billStatus === '2' &&
                            ids.push($scope.dataList[i].billId);
                        } else {
                            ybWidget.ShowMessage('请选择未同步和同步失败的单据进行同步!');
                            return;
                        }
                    }
                }
                if (ids.length === 0) {
                    ybWidget.ShowMessage('请选择需要同步的行');
                    return;
                }
                var service = "device";
                var reqUrl = "/purchaseRequest/createContract";
                ybHttp.Post(service, reqUrl, ids).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '同步成功');
                    getDataList();
                });
                // ybWidget.ShowMessage("确认从CRM同步数据吗？", MESG_TYPE.Ask).then(function () {
                //     var service = "device";
                //     var reqUrl = "/purchaseRequest/createContract";
                //     ybHttp.Get(service, reqUrl).then(function () {})
                //     ybWidget.ShowMessage("正在后台同步请稍后", MESG_TYPE.Note);
                // }, function () {});
            };

            function getOrderStatues() {
                var service = "device";
                var reqUrl = "/dataDictionary/searchList";
                var param = {
                    parentCode: "SPZT"
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.billStateList = resp.value;
                })
            }

            $scope.delApply = function (item) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/purchaseRequest/remove";
                    var param = {};
                    param.billId = item.billId;
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        $scope.refreshData();
                    });
                })
            };
            $scope.importDate = function () {
                var param = {
                    name: "采购申请",
                    templateReqService: "device",
                    templateReqUrl: "/purchaseRequest/downloadOverSeaPurExcel",
                    importReqService: "device",
                    importReqUrl: "/purchaseRequest/importOverSeaPurExcel",
                    importErrorUrl: ""
                };
                ybWidget.ImportFile(param).then(function (data) {
                    getDataList(1);
                });
            };
            // 校验所选零件是否属于 客户指定供方和产品
            function checkMaterial() {
                var param = {
                    materialNos: $scope.orderObj.materialsList.map(m => m.materialsNo),
                    purchaseOrgId: $scope.orderObj.supplierOrgId
                };
                return ybHttp.Post("device", "/purchaseRequest/vendorSuppliedProductVerify", param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return [];
                    }
                    return resp.value || []
                }, function() {
                    return [];
                })
            }

            function getDetail(item, type) {
                var param = {
                    billId: item.billId
                };
                ybHttp.Get('device', '/purchaseRequest/item', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.orderObj = resp.value;
                    if(!!$scope.orderObj.deliveryDate){
                        $scope.orderObj.deliveryDate = new Date($scope.orderObj.deliveryDate)
                    }
                    angular.forEach($scope.orderObj.logDOList, function (item) {
                        if (!!item.operationTime) {
                            item.operationTimeShow = $filter('YbDate')(item.operationTime, 'yyyy-MM-dd HH:mm:ss');
                        }
                    });
                    angular.forEach($scope.orderObj.materialsList, function (item) {
                        item.estimatedShippingDateShow = $filter("YbDate")(item.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');
                        item.deliveryDateStr = $filter("YbDate")(item.deliveryDate, 'yyyy-MM-dd');

                        item.saleDelStatusShow = $filter("TrueOrFalseOrNull")(item.saleDelStatus);
                        item.saleDelTimeShow = $filter("YbDate")(item.saleDelTime, 'yyyy-MM-dd');

                        item.totalOuter = item?.outWarehouseVO?.totalOuter;
                        item.totalInner = item?.outWarehouseVO?.innerWarehouse;

                        item.isDirectCastShow = $filter("TrueOrFalseOrNull")(item.isDirectCast);

                        if (type == 'audit') {
                            const isRaiseRes = Number(isNeedRaiseFun($scope.orderObj, item));
                            if (isRaiseRes) {
                                item.addRateType = 1; // 写死1：1的意思是加价5%，不然审核拒绝时接口会报空指针
                                item.isChecked = true;
                                item.settlementPrice = $filter("decimalCover")(raisePrice(item.settlementPrice), 2);
                                item.applyTotalPrice = $filter("decimalCover")(ybWidget.Times(item.settlementPrice, item.qty), 2);
                            }

                            item.isRaise = isRaiseRes;
                        }
                    });
                    setTotalPriceAdjust();
                    $scope.tabFlag.name = tabFlag[2];
                    if (type == 'audit') {
                        if (!$scope.isZHJCH) {
                            changeMatetailConfig();
                        }

                        if ($scope.isWJ) {
                            checkMaterial().then(res => {
                                if (res.length > 0) {
                                    ybWidget.ShowMessage('请查看报告！', MESG_TYPE.Error, { title: '提供指定供方及产品申请报告的提醒' })
                                }
                            })
                        }
                        $scope.remarkEditable = $scope.isWJ && ['1', '3'].includes($scope.orderObj.purchaseType) // 紧急、整改的备注可以编辑
                        $scope.changeTab(1);
                    }
                    if (type == 'edit') {
                        $scope.changeTab(2);
                    }
                    if (type == 'view') {
                        $scope.changeTab(3);
                    }
                    // 塔机的为下拉框字典需要映射
                    if ($scope.isTJ) {
                        $scope.orderObj.modelName = $scope.TJJXList.find(c => c.code == $scope.orderObj.model)?.name
                        $scope.orderObj.model =  $scope.TJJXList.find(c => c.code == $scope.orderObj.model)
                    }
                });
            }

            function isNeedRaiseFun(headerInfo, material) {
                // isUrgentPrice 是企业信息表COMPANY_INFO里的字段，目前只有挖机是1
                // purchaseType 一级采购方式 1：紧急 2：补库 3：整改 等等
                // purchaseTypeChildId 二级采购方式
                let needRaiseRes = headerInfo.isUrgentPrice && headerInfo.purchaseType === '1'
                if ($scope.isWJ && needRaiseRes) {
                    if (window.JCHK_ORG_IDs.includes(headerInfo.purchasePlatOrgId)) { // 客户是进出口：不加价
                        needRaiseRes = false;
                    } else if (headerInfo.purchaseTypeChildId === 'A1') { // 一级=紧急，二级=三包：不加价
                        needRaiseRes = false;
                    } else if (headerInfo.purchaseTypeChildId === 'A2') { // 一级=紧急，二级=销售
                        needRaiseRes = headerInfo.totalValue <= 30000; // 订单金额大于3万：不加价
                    }
                }

                if (needRaiseRes) {
                    ybWidget.GetTableCol($scope.auditMaterielTableConfig.tableCol, 'isNeedRaise').hidden = false;
                    $scope.auditMaterielTableConfig.scrollWidth = 1080;
                }
                return needRaiseRes;
            }

            $scope.handleJiajiaCheck = function (item, dataField) {
                var tempPrice = "";
                if (item['isChecked'] === false) {
                    tempPrice = resetRaisePrice(item.settlementPrice)
                    item.isRaise = 0
                } else {
                    tempPrice = raisePrice(item.settlementPrice)
                    item.isRaise = 1
                }
                item.settlementPrice = $filter("decimalCover")(tempPrice, 2);
                item.applyTotalPrice = ybWidget.Times(item.settlementPrice, item.qty);

                setTotalPriceAdjust();
            };

            function raisePrice(price) {
                return ybWidget.Times(price, 1+0.05);
            }
            function resetRaisePrice(price) {
                return ybWidget.Divide(price, 1+0.05);
            }

            function changeMatetailConfig() {
                var col = [];
                angular.forEach($scope.tableCol, function (item) {
                    if (item.dataField === 'priceSchemeName') {
                        item.inputType = '';
                    }
                    col.push(item);
                });
                $scope.auditMaterielTableConfig.tableCol = col;
            }

            $scope.editApply = function (item) {
                $scope.tabFlag.type = 1;
                getDetail(item, 'edit');
            };

            function viewDetail(item) {
                ybWidget.GetTableCol($scope.auditMaterielTableConfig.tableCol, 'isNeedRaise').hidden = true;
                $scope.auditMaterielTableConfig.scrollWidth = 1000;
                getDetail(item, 'view');
            }

            $scope.selectDealer = function () {
                ybWidget.DataSelector({
                    title: '客户',
                    url: '/companyDealer/list',
                    otherParams: { swyPurchaseApplyDealerList: $scope.isSWY ? 1 : null },
                    keyWords: [{label: '客户编号', field: 'dealerCode'}, {label: '客户名称', field: 'companyName'}],
                    fields: [
                        {
                            name: '客户名称',
                            dataField: 'companyName',
                            width: "60%"
                        },
                        {
                            name: '客户编号',
                            dataField: 'dealerCode',
                            width: "40%"
                        }
                    ]
                }).then(function (data) {
                    if (!!$scope.orderObj.purchaseOrgId && (data.dealerOrgId !== $scope.orderObj.purchaseOrgId)) {
                        clearMateriel();
                    }
                    $scope.orderObj.purchaseOrgName = data.companyName;
                    $scope.orderObj.purchaseOrgId = data.dealerOrgId;
                    $scope.orderObj.jckPriceFlag = data.jckPriceFlag;
                    getDirectLimit();
                })
            };

            function getDirectLimit() {
                var service = "device";
                var reqUrl = "/companyDealer/getDirectLimitApply";
                var param = {
                    orgId: $scope.orderObj.purchaseOrgId
                };

                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    $scope.orderObj.directLimit = resp;
                })
            }

            $scope.selectSold = function () {
                if (!$scope.orderObj.supplierOrgId) {
                    return;
                }
                var param = {
                    name: "供货商",
                    type: "supplier",
                    soldOrgId: $scope.orderObj.supplierOrgId,
                    isDirect: 1
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.soldOrgId = data.supplierOrgId;
                    $scope.orderObj.soldOrgName = data.companyName;
                    clearMateriel();
                })
            };

            $scope.clearSold = function () {
                $scope.orderObj.soldOrgId = "";
                $scope.orderObj.soldOrgName = "";
                clearMateriel();
            };

            function clearMateriel() {
                $scope.orderObj.materialsList = [];
                $scope.markInfo.allCheckedMaterial = false;
                $timeout(function () {
                    if (!$scope.orderObj.purchaseOrgId) {
                        EventBus.Publish("clearMaterial");
                    } else {
                        EventBus.Publish("getMaterial");
                    }
                });
            }

            $scope.selectDispatch = function () {
                var param = {
                    name: "调度员",
                    type: 'staffByWorkspace',
                    supplierOrgId: $scope.curUser.spaceId
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.condition.dispatcherName = data.name;
                    $scope.condition.dispatcherId = data.userId;
                })
            };


            $scope.searchDispatch = function () {
                var param = {
                    name: "调度员",
                    type: 'staffByWorkspace',
                    supplierOrgId: $scope.curUser.spaceId,
                    fuzzyFlag: '1', // 1 模糊 0 精准查询
                    defaultRoleName: ''
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.dispatcherName = data.name;
                    $scope.orderObj.dispatcherId = data.userId;
                })
            };

            $scope.changeMaterialsType = function() {
                $scope.orderObj.materialsList = [];
            };

            $scope.selMateriel = function (e) {
                if (!!$scope.toolbarConfig.showMateriel) {
                    e.stopPropagation();
                } else {
                    if (!$scope.orderObj.purchaseOrgId) {
                        ybWidget.ShowToaster('error', '请选择客户');
                        return;
                    }
                    if ($scope.orderObj.isDirectCast && !$scope.orderObj.soldOrgId && $scope.orderObj.isDirectCast == 1) {
                        ybWidget.ShowToaster('error', '请选择供货商');
                        return;
                    }

                    /* if ($scope.isWJ && !$scope.orderObj.materialsType) {
                        ybWidget.ShowToaster('error', '请选择零件类型');
                        return;
                    } */

                    $timeout(function () {
                        $scope.toolbarConfig.showMateriel = true;
                        EventBus.Publish("getMaterial");
                    });
                }
            };

            $scope.importMateriel = function () {
                if (!$scope.orderObj.purchaseOrgId) {
                    ybWidget.ShowToaster('error', '请选择客户');
                    return;
                }

                /* if ($scope.isWJ && !$scope.orderObj.materialsType) {
                    ybWidget.ShowToaster('error', '请选择零件类型');
                    return;
                } */

                var param = {
                    name: "零件",
                    templateReqService: "device",
                    templateReqUrl: "/purchaseRequest/download",
                    importReqService: "device",
                    importReqUrl: "/purchaseRequest/import",
                    importErrorUrl: "",
                    dealerOrgId: $scope.orderObj.purchaseOrgId,
                    isDirectCast: $scope.orderObj.isDirectCast,
                    jckPriceFlag: $scope.orderObj.jckPriceFlag,
                    otherParams: {
                        'x-materialsType': $scope.orderObj.materialsType
                    }
                };
                ybWidget.ImportFile(param).then(function (data) {
                    angular.forEach(data, function (item) {
                        item.isChecked = false;
                        item.totalOuter = item?.outWarehouseVO?.totalOuter;
                        item.totalInner = item?.outWarehouseVO?.innerWarehouse;
                    });
                    $scope.orderObj.materialsList = [];
                    $scope.orderObj.materialsList = angular.copy(data);
                });
            };

            $scope.delMateriel = function (item, index) {
                ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                    $scope.orderObj.materialsList.splice(index, 1);
                    EventBus.Publish("setMaterial", item.materialsNo);

                    reSetDeliveryDateByMaterialsMax();
                });
            };

            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.orderObj.materialsList.length; i < len; i++) {
                    if (!!$scope.orderObj.materialsList[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.orderObj.materialsList.length - 1; i >= 0; i--) {
                        if (!!$scope.orderObj.materialsList[i].isChecked) {
                            $scope.orderObj.materialsList.splice(i, 1);
                        }
                    }
                    if ($scope.orderObj.materialsList.length === 0) {
                        $scope.markInfo.allCheckedMaterial = false;
                    }
                    EventBus.Publish("setMaterial");

                    reSetDeliveryDateByMaterialsMax();
                });
            };

            $scope.countTotal = function (item) {
                item.qtyErr = false;
                item.qtyFormatErr = false;
                if (!item.qty || parseFloat(item.qty) <= 0) {
                    item.qtyErr = true;
                    return;
                }
                if (item.isMinimumBuy && ybWidget.Remainder(item.qty, item.minimumBuy) > 0) {
                    item.qtyFormatErr = true;
                    return;
                }
                if (item.qty > 9999999.999) {
                    item.qty = 9999999.999;
                }
                item.applyTotalPrice = $filter("decimalCover")(ybWidget.Times(item.qty, item.settlementPrice), 2);
                calcOrderTotalValue();
            };

            $scope.checkMachineModel = function (item){
                item.machineModelEmptyErr = false;
                if(!item.machineModel || item.machineModel.length == 0){
                    item.machineModelEmptyErr = true;
                    return;
                }
            };

            EventBus.Subscribe("onMaterialChange", handleMaterialChange);
            function handleMaterialChange(item) {
                calcOrderTotalValue();
                setDeliveryDateByMaterialsMax(item);
            }

            function calcOrderTotalValue() {
                $scope.orderObj.totalValue = 0;
                angular.forEach($scope.orderObj.materialsList, function (item) {
                    $scope.orderObj.totalValue += (+item.applyTotalPrice || 0);
                });
                $scope.orderObj.totalValue = $filter("decimalCover")($scope.orderObj.totalValue, 2);
            }

            $scope.auditApply = function (item) {
                ybWidget.GetTableCol($scope.auditMaterielTableConfig.tableCol, 'isNeedRaise').hidden = true;
                $scope.auditMaterielTableConfig.scrollWidth = 1000;
                getDetail(item, 'audit');
            };
            // 判断数组中的值是否都相等
            $scope.isAllEqual = function (array) {
                if (array.length > 0) {
                    return !array.some(function (value, index) {
                        return value !== array[0];
                    });
                } else {
                    return true;
                }
            };
            $scope.saveData = function (type, valid) {
                // 塔机主机厂 机型必填
                if ($scope.isTJ) {
                    if (!$scope.orderObj.model) {
                        ybWidget.ShowToaster('error', '机型是必填项');
                        return  
                    }
                }
                if (!valid) {
                    $scope.submitted = true;
                    return;
                }
                var listValid = true;
                var service = "device";
                var reqUrl = "/purchaseRequest/save";
                if (type === 'submit') {
                    if ( window.CHY_ORG_IDs.includes($scope.orderObj.supplierOrgId)) {
                        // 判断零件属性是否一致    
                        const arr = [] 
                        $scope.orderObj.materialsList.forEach(item => {
                            arr.push(item.productPropClass)
                        })
                        if (!$scope.isAllEqual(arr)) {
                            ybWidget.ShowToaster('error', '铲运要分订单提报！');
                            return                             
                        }                                           
                    }                    
                    reqUrl = "/purchaseRequest/submit";
                    if (!$scope.orderObj.materialsList || $scope.orderObj.materialsList.length == 0) {
                        ybWidget.ShowToaster('error', '零件不可为空');
                        return;
                    }
                }

                if (!$scope.isDL && !$scope.isZHL) {
                    $scope.orderObj.deliveryDate = new Date($scope.orderObj.deliveryDate).getTime();
                }
                var param = angular.copy($scope.orderObj);
                param.shippingMethod = $scope.orderObj.shippingMethod;
                param.seller = true;
                for (var i = 0, len = $scope.orderObj.materialsList.length; i < len; i++) {
                    $scope.orderObj.materialsList[i].qtyErr = false;
                    $scope.orderObj.materialsList[i].qtyFormatErr = false;
                    $scope.orderObj.materialsList[i].machineModelEmptyErr = false;
                    if (!$scope.orderObj.materialsList[i].qty || parseFloat($scope.orderObj.materialsList[i].qty) <= 0) {
                        $scope.orderObj.materialsList[i].qtyErr = true;
                        listValid = false;
                        break;
                    }
                    if ($scope.orderObj.materialsList[i].isMinimumBuy && ybWidget.Remainder($scope.orderObj.materialsList[i].qty, $scope.orderObj.materialsList[i].minimumBuy) > 0) {
                        $scope.orderObj.materialsList[i].qtyFormatErr = true;
                        listValid = false;
                        break;
                    }

                    if($scope.isJCHK) {
                        if (!$scope.orderObj.materialsList[i].machineModel || $scope.orderObj.materialsList[i].machineModel.length == 0) {
                            $scope.orderObj.materialsList[i].machineModelEmptyErr = true;
                            listValid = false;
                            break;
                        }
                    }

                    if ($scope.isDL || $scope.isZHL) {
                        if (!$scope.orderObj.materialsList[i].deliveryDate) {
                            $scope.orderObj.materialsList[i].dateErr = true;
                            listValid = false;
                            break;
                        }
                    }
                }
                if (!listValid) {
                    return;
                }
                if ($scope.isTJ) {
                    const { code = '', name = '' } = $scope.orderObj.model || {}
                    param.model = code
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    if ($scope.tabFlag.type === 0) {
                        clearSortParam();
                        getDataList(1);
                    } else {
                        getDataList();
                    }
                    $scope.changeTab(0);
                });
            };

            $scope.auditPurchase = function (type, id, message, isDirect) {
                var service = "device";
                var reqUrl = "/purchaseRequest/auditPass";
                if (type === "refuse") {
                    if (!message) {
                        ybWidget.ShowMessage('请输入审核意见');
                        $scope.submitted = true;
                        return;
                    }
                    reqUrl = "/purchaseRequest/auditRefused";
                }
                if ($scope.isTJ) {
                    const { code = '', name = '' } = $scope.orderObj.model || {}
                    $scope.orderObj.model = code
                }
                ybHttp.Post(service, reqUrl, $scope.orderObj).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    if (type === "pass" && !isDirect && $scope.orderObj.billTypeMode!='合同') {
                        ybWidget.ShowMessage("审核通过，是否立即新增销售订单？", MESG_TYPE.Ask).then(function () {
                            $state.go("app.sales.sellIntention", {
                                billId: id
                            })
                        }, function () {

                        })
                    }
                    getDataList();
                    $scope.changeTab(0);
                });
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            $scope.importAttach = function (item) {
                var param = {
                    name: "附件",
                    hideTemplate: true,
                    ignoreFormat: true,
                    importReqService: "device",
                    importReqUrl: "/purchaseRequest/importAttach",
                    importErrorUrl: "",
                    billId: item.billId
                };
                ybWidget.ImportFile(param).then(function (data) {
                    getDataList(1);
                });
            };
            $scope.searchAddress = function (receiverName, purchaseOrgId) {
                if (!purchaseOrgId) {
                    ybWidget.ShowToaster('warning', '请先选择客户');
                    return;
                }
                ybWidget.SelectDeliveryAddress({
                    deliveryName: receiverName,
                    clientOrgId: purchaseOrgId,
                    clientReceiveInfo: $scope.sapNum,
                    supplierOrgId: $scope.orderObj.supplierOrgId
                }).then(function (data) {
                    $scope.orderObj.receiverName = data.receiverName;
                    $scope.orderObj.receiverTel = data.receiverTel;
                    $scope.orderObj.receiverAddress = data.receiverAddress;
                    $scope.orderObj.addressCode = data.addressCode;
                });
            };

            $scope.$on("$destroy", function () {
                EventBus.Unsubscribe("onMaterialChange", calcOrderTotalValue);
            });

            function setPriceScheme(item, index, priceScheme) {
                var settlementPrice;
                item.priceSchemeId = priceScheme.activityId;
                item.priceSchemeName = priceScheme.name;

                if (item.isRaise) {
                    settlementPrice = $filter("decimalCover")(raisePrice(priceScheme.discountPrice), 2);
                } else {
                    settlementPrice = $filter("decimalCover")(priceScheme.discountPrice, 2);
                }

                $scope.orderObj.materialsList[index].settlementPrice = settlementPrice;
                if (item.qty !== "") {
                    setAdjustPrice(item, "qty");
                }
            }

            function setAdjustPrice(item, colItem) {
                item.qtyAdjustErr = false;
                item.priceAdjustErr = false;

                if (!item.qty || parseFloat(item.qty) <= 0) {
                    item.qtyAdjustErr = true;
                    return;
                }
                if (!item.settlementPrice || parseFloat(item.settlementPrice) <= 0) {
                    item.priceAdjustErr = true;
                }
                if (item.qty > 9999999.999) {
                    item.qty = 9999999.999;
                }
                if (angular.isUndefined(item[colItem]) || item[colItem] === "") {
                    item.applyTotalPrice = ""
                } else {
                    item.applyTotalPrice = $filter("decimalCover")(ybWidget.Times(item.qty, item.settlementPrice), 2);
                }
                setTotalPriceAdjust();
            }

            function setTotalPriceAdjust() {
                var totalPrice = 0;
                angular.forEach($scope.orderObj.materialsList, function (item) {
                    if (!item.applyTotalPrice) {
                        return false;
                    }
                    totalPrice = ybWidget.Plus(totalPrice, parseFloat(item.applyTotalPrice));
                });
                $scope.orderObj.settleValue = $filter("decimalCover")(totalPrice, 2);
                $scope.orderObj.totalValue = $scope.orderObj.settleValue;
            }


            //选择价格方案后回调
            $scope.chosePriceScheme = function (item, index) {
                var clientId = $scope.orderObj.purchaseOrgId;
                if (!clientId) {
                    ybWidget.ShowToaster('error', '请选择客户');
                    return;
                }

                var param = {
                    schemeType: 0,
                    apiObj: {
                        param: {
                            dealerOrgId: clientId,
                            materialsNo: item.materialsNo
                        }
                    }
                };
                ybWidget.PriceSchemeSelector(param).then(function (data) {
                    setPriceScheme(item, index, data);
                })
            };

            $scope.$watch('orderObj.jckPriceFlag', function(newVal) {
                // 判断零件是否进出口 0 否 (可选)1 是(不可选) showPricePlan
                if (window.JCHK_ORG_IDs.includes($scope.orderObj.supplierOrgId)){
                    if ($scope.orderObj.jckPriceFlag == 1) {    
                        $scope.showPricePlan = false
                    }else if($scope.orderObj.jckPriceFlag == 0){  
                        $scope.showPricePlan = true
                    }
                }else {
                    $scope.showPricePlan = true
                }
            })  
            /**
             * 批量选择价格方案
             */
            $scope.batchChosePriceScheme = function () {
                var clientId = $scope.orderObj.purchaseOrgId;
                if (!clientId) {
                    ybWidget.ShowToaster('error', '请选择客户');
                    return;
                }
                
                var param = {
                    isBatch: true,
                    schemeType: 0,
                    apiObj: {
                        param: {
                            dealerOrgId: clientId,
                        }
                    }
                };
                ybWidget.PriceSchemeSelector(param).then(function (data) {
                    const priceSchemeId = data.id;
                    for (var i = 0; i < $scope.orderObj.materialsList.length; i++) {
                        var materialItem = $scope.orderObj.materialsList[i];
                        var priceSchemeList = materialItem.marketingActivityPriceVOList || [];
                        var priceScheme = getPriceScheme(priceSchemeId, priceSchemeList);
                        if (priceScheme != null) {
                            setPriceScheme(materialItem, i, priceScheme);
                        }
                    }
                    function getPriceScheme(id, list) {
                        for (var j = 0; j < list.length; j++) {
                            if (id == list[j].activityId) {
                                return list[j];
                            }
                        }
                        return null;
                    }
                });
            };

            //清除价格方案
            $scope.clearPriceScheme = function (item) {
                item.isRaise = 0;
                item.isChecked = false;
                
                item.priceSchemeId = "";
                item.priceSchemeName = "";

                item.settlementPrice = item.price;
                item.applyTotalPrice = item.qty * item.price;

                setTotalPriceAdjust();
            };

            $scope.jiaohuoDateChangeBatch = function(val) {
                angular.forEach($scope.orderObj.materialsList, function(item) {
                    item.deliveryDate = val;
                })

                if (!$scope.isDL && !$scope.isZHL) return;
                $scope.orderObj.deliveryDate = val;
            };

            $scope.switchListDatePicker = function (item) {
                angular.forEach($scope.orderObj.materialsList, function (item) {
                    item.showDatePicker = false;
                });
                item.showDatePicker = true;
            };

            $scope.jiaohuoDateChange = function() {
                reSetDeliveryDateByMaterialsMax()
            };

            function setDeliveryDateByMaterialsMax({ selectedItem }) {
                if (!$scope.isDL && !$scope.isZHL) return;

                const orgIds = window.JCHK_ORG_IDs.concat(window.BX_ORG_IDs);
                if (!orgIds.includes($scope.orderObj.purchaseOrgId)) {
                    selectedItem.deliveryDate = undefined;
                } else {
                    // 客户为：巴西、进出口
                    if (!$scope.orderObj.deliveryDate || $scope.orderObj.deliveryDate < selectedItem.deliveryDate) {
                        $scope.orderObj.deliveryDate = selectedItem.deliveryDate
                    }
                }
            }

            function reSetDeliveryDateByMaterialsMax() {
                if (!$scope.isDL && !$scope.isZHL) return;

                let deliveryDates = $scope.orderObj.materialsList.map(item => item.deliveryDate).filter(Boolean);
                deliveryDates = deliveryDates.sort(function(a, b) {
                    if (a > b) return -1
                    if (a == b) return 0
                    if (a < b) return 1
                })
                $scope.orderObj.deliveryDate = deliveryDates[0];
            }

            function waibuStock(item) {
                const param = {
                    title: '外部库存',
                    fields: [
                        { name: '仓库编号', dataField: 'warehouse', width: '30%' },
                        { name: '仓库描述', dataField: 'warehouseName', width: '40%' },
                        { name: '库存', dataField: 'num', width: '30%' }
                    ],
                    data: item?.outWarehouseVO?.outerWarehouseItems || []
                }
                ybWidget.DatasShow(param);
            }

            function getTJJXType(){
                var service = "device";
                var reqUrl = "/serviceBasicDataAgent/searchList";
                var param = {pCode:"TJJX"};
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.TJJXList =resp.value;
                });
            };

            $scope.notReviewedForOneClick = function(){
                console.log($scope.condition.notReviewedForOneDayCond);
            };
            $scope.oneMonthUnfinishedClick = function(){
                console.log($scope.condition.oneMonthUnfinishedCond);
            };

            $scope.importDataList = [];
            $scope.importPriceBatch = function() {
                var param = {
                    name: "价格",
                    templateReqService: "device",
                    templateReqUrl: "/purchaseRequest/downloadPriceExcel",
                    importReqService: "device",
                    importReqUrl: "/purchaseRequest/importPriceExcel",
                    importErrorUrl: ""
                };
                ybWidget.ImportFile(param).then(function (data) {
                    $scope.importDataList = data || [];
                });
            };

            $scope.handleAdjustPrice = function() {
                if ($scope.importDataList.length == 0) {
                    ybWidget.ShowMessage("请先导入数据", MESG_TYPE.Error);
                    return;
                }

                var service = "device";
                var reqUrl = "/purchaseRequest/adjustPrice";
                ybHttp.Post(service, reqUrl, { priceList: $scope.importDataList }).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }

                    ybWidget.ShowMessage("操作成功", MESG_TYPE.Success);
                    $scope.importDataList = [];
                });
            };

            (function () {
                getTJJXType()
                // 智联查询条件的默认管理员删掉
                if (!$scope.isZL) {
                    $scope.condition.dispatcherName = $scope.curUser.name;
                    $scope.condition.dispatcherId = $scope.curUser.userId;
                }

                if ($scope.isWJ) {
                    $scope.condition.showDel = true
                }

                if ($scope.isDL || $scope.isZHL){
                    $scope.condition.notReviewedForOneDayCond = 0
                    $scope.condition.oneMonthUnfinishedCond = 0
                }
                
                UserContextService.SetBtnPermission(setBtnPermission);

                // 如果是从首页代办事项跳转过来的，给高级搜索筛选条件赋值
                console.log("$state.params:",$state.params);
                if ($state.params.notReviewedForOneDayCond){
                    // 采购申请预警：一天未审核
                    $scope.condition.notReviewedForOneDayCond = 1;
                    $scope.condition.dispatcherName = null;
                    $scope.condition.dispatcherId = null;
                    $scope.condition.createName = $scope.curUser.name;
                }else if ($state.params.notEndedForOver1MonthCond){
                    // 采购申请预警：一月未完结
                    $scope.condition.oneMonthUnfinishedCond = 1;
                    $scope.condition.dispatcherName = null;
                    $scope.condition.dispatcherId = null;
                    $scope.condition.createName = $scope.curUser.name;
                }else if ($state.params.purchaseNo){
                    // 从发票管理跳转过来的
                    $scope.condition.billNos = $state.params.purchaseNo;
                }
               
                getDataList();
                getOrderStatues();
                $scope.setFixedWidth();

                if ($scope.needHide) {
                    $scope.tableConfig.tableCol = ybWidget.HideTableCols($scope.tableConfig.tableCol, ['delShow', 'updateDateShow']);
                }
            })();
        }]);
})(window, window.angular);
